<template>
  <page-header-wrapper :title="false">
    <a-card :bordered="false" :style="{margin:'0 -24px',padding:0}">
      <div class="table-operator" v-action:add>
        <a-button type="primary" icon="plus" @click="handleAdd">新建</a-button>
      </div>
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="5" :sm="24">
              <a-form-item label="分类">
                <a-select :allowClear="true" v-model="queryParam.class_id" placeholder="请选择分类" default-value="0">
                  <a-select-option v-for="(item, index) in classList" :key="index" :value="item.id">
                    {{ item.class_name }}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :md="7" :sm="24">
              <a-form-item label="标题">
                <a-input :allowClear="true" v-model="queryParam.title" placeholder="请输入标题"/>
              </a-form-item>
            </a-col>
            <a-col :md="7" :sm="24">
              <span class="table-page-search-submitButtons" :style="{ float: 'right', overflow: 'hidden' }">
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="resetSearchForm()">重置</a-button>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <s-table
        ref="table"
        size="default"
        rowKey="id"
        :columns="columns"
        :data="loadData"
        showPagination="auto"
      >
        <span slot="status" slot-scope="text">
          <a-badge :status="text | statusTypeFilter" :text="text | statusFilter" />
        </span>
        <span slot="answers_count" slot-scope="text, r">
          <a href="#" @click="tolog(r)">{{ text }}</a>
        </span>
        <span style="text-align: center;" slot="action" slot-scope="text, record">
          <template>
            <a @click="totiku(record)">题库</a>
            <a-divider type="vertical" v-action:info/>
            <a @click="handleSub(record)" v-action:info>详情</a>
            <a-divider type="vertical" v-action:info/>
            <a @click="showQr(record)" v-action:info>获取分享</a>
            <a-divider type="vertical" v-action:edit/>
            <a @click="handleEdit(record)" v-action:edit>编辑</a>
            <a-divider type="vertical" v-action:del/>
            <a @click="handleRemove(record)" v-action:del>删除</a>
          </template>
        </span>
      </s-table>
      <!-- 增/查/改 弹出模板 -->
      <create-form
        ref="createModal"
        :visible="visible"
        :loading="confirmLoading"
        :model="mdl"
        :classList="classList"
        @cancel="handleCancel"
        @ok="handleOk"
        :okHidden="okHidden"
        :serveList="serveList"
      />
      <!-- 删除/停用确认窗 -->
      <a-modal
        title="提示"
        :visible="modal.show"
        :confirm-loading="modal.loading"
        @ok="modal.confirm"
        @cancel="modal.show = false"
      >
        <p>{{ modal.text }}</p>
      </a-modal>
      <!-- <step-by-step-modal ref="modal" @ok="handleOk"/> -->
    </a-card>
    <a-modal
      :title="model_title"
      :visible="qr.show"
      :confirm-loading="qr.loading"
      @ok="qr.show = false"
      @cancel="qr.show = false"
    >
      <div style="width: 128px; height: 128px;margin: 0 auto;" id="qrcode"></div>
      <div style="">
        <div>问卷链接</div>
        <div> {{ qrUrl }}</div>
      </div>
    </a-modal>
  </page-header-wrapper>
</template>

<script>
import { STable } from '@/components'
import { serviceList, serviceContentChangeStatus } from '@/api'
import CreateForm from './modules/CreateForm'
import QRCode from 'qrcodejs2'
import { sortList, surveyAdd, surveyList, surveyEdit, surveyInfo, surveyDel } from '@/api/exam'
const statusMap = {
  2: {
    status: 'default',
    text: '停用'
  },
  1: {
    status: 'success',
    text: '启用'
  }
}

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    align: 'center'
  },
  {
    title: '标题',
    dataIndex: 'title',
    align: 'center'
  },
  {
    title: '分类',
    dataIndex: 'class_name',
    align: 'center'
  },
  {
    title: '出题类型',
    dataIndex: 'type_name',
    align: 'center',
    scopedSlots: { customRender: 'type_name' }
  },
  {
    title: '答题记录',
    dataIndex: 'answers_count',
    align: 'center',
    scopedSlots: { customRender: 'answers_count' }
  },
  {
    title: '状态',
    dataIndex: 'status',
    align: 'center',
    scopedSlots: { customRender: 'status' }
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '300px',
    align: 'center',
    scopedSlots: { customRender: 'action' }
  }
]

export default {
  components: {
    STable,
    CreateForm
  },
  data () {
    this.columns = columns
    return {
      // create model
      visible: false,
      confirmLoading: false,
      okHidden: false,
      mdl: {
        start_time: '',
        end_time: '',
        num: '',
        detailed_rules: '',
        type: 1,
        status: 1,
        class_id: '',
        img: [],
        title: ''
      },
      qr: {
        show: false,
        loading: false
      },
      classList: [], // 问卷分类
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: async parameter => {
        const params = {
          page: parameter.pageNo,
          per_page: parameter.pageSize
        }
        const res = await surveyList({
          ...params,
          ...this.queryParam
        })
        const result = {
          pageNo: res.current_page,
          totalPage: res.last_page,
          data: res.data,
          pageSize: 10,
          totalCount: res.total
        }
        return Promise.resolve(result)
      },
      modal: {
        show: false,
        text: '',
        loading: false,
        confirm: () => {},
        cancel: () => {}
      },
      serveList: [],
      selectedRowKeys: [],
      selectedRows: [],
      qrcode: null,
      qrUrl: '',
      model_title: ''
    }
  },
  computed: {
    rowSelection () {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: this.onSelectChange
      }
    }
  },
  filters: {
    statusFilter (type) {
      return statusMap[type].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    }
  },
  created () {
    serviceList().then(res => {
      this.serveList = res.list
    })
    this.getsortList()
  },
  methods: {
    tolog (item) {
      this.$router.push({
        path: '/admin/exam/AnswerLog',
        query: {
          id: item.id
        }
      })
    },
    totiku (item) {
      this.$router.push({
        path: '/admin/exam/QuestionBank',
        query: {
          id: item.id
        }
      })
    },
    showQr (item) {
      this.qr.show = true
      this.model_title = item.title
      this.$nextTick(() => {
        // if (item.id < 11) {
        //    this.qrUrl = 'https://testhphone.tokenbty.com/#/question/info?cate=' + item.id
        // } else {
        //    this.qrUrl = 'https://testhphone.tokenbty.com/#/question/info?id=' + item.id
        // }
        this.qrUrl = 'https://hphone.tokenbty.com/#/question/info?id=' + item.id
        if (this.qrcode) {
          this.qrcode.clear()
          this.qrcode.makeCode(this.qrUrl)
        } else {
          this.qrcode = new QRCode('qrcode', {
            text: this.qrUrl,
            width: 128,
            height: 128,
            colorDark: '#000000',
            colorLight: '#ffffff',
            correctLevel: QRCode.CorrectLevel.H
          })
        }
      })
    },
    getsortList () {
      sortList({ type: 'select' }).then((res) => {
        // console.log('分类列表', res)
        this.classList = res.list
      })
    },
    handleAdd () {
      this.visible = true
      this.mdl = {
        start_time: '',
        end_time: '',
        num: '',
        detailed_rules: '',
        type: 1,
        status: 1,
        class_id: '',
        img: [],
        title: ''
      }
    },
    handleEdit (record) {
      this.visible = true
      this.confirmLoading = true
      surveyInfo({ id: record.id }).then((res) => {
        this.mdl = res
        this.mdl['times'] = [res.start_time, res.end_time]
        this.confirmLoading = false
      })
    },
    handleOk () {
      const form = this.$refs.createModal.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          const success = (res, info) => {
            if (res.is_ok == 'Y') {
              this.handleVisible()
              form.resetFields()
              this.$refs.table.refresh()
              this.$message.info(info)
            }
          }
          const final = () => { this.confirmLoading = false }
          console.log(values)
          values.img = values.img[0].url
          if (values.id > 0) {
            surveyEdit({ ...values, image: values?.image?.[0].url })
              .then(res => success(res, '修改成功'))
              .finally(final)
          } else {
            surveyAdd({ ...values, image: values?.image?.[0].url })
              .then(res => success(res, '新增成功'))
              .finally(final)
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleChangeStatus (record) {
      this.openModal(serviceContentChangeStatus, record, '撤回')
    },
    openModal (method, record, statusText) {
      this.modal = {
        ...this.modal,
        text: `确定${ statusText }该内容吗？`,
        show: true,
        confirm: async () => {
          try {
            this.modal.loading = true
            const res = await method(record)
            if (res.is_ok == 'Y') {
              this.modal.loading = false
              this.modal.show = false
              this.$refs.table.refresh()
              this.$message.info(`${ statusText }成功`)
            }
          } catch (err) {
            console.warn(err)
            this.modal.loading = false
          }
        }
      }
    },
    handleCancel () {
      this.mdl = {
        start_time: '',
        end_time: '',
        num: '',
        detailed_rules: null,
        type: 1,
        status: 1,
        class_id: '',
        img: [],
        title: ''
      }
      this.handleVisible()
      const form = this.$refs.createModal.form
      form.resetFields() // 清理表单数据（可不做）
    },
    handleSub (record) {
      this.okHidden = true
      this.visible = true
      this.confirmLoading = true
      surveyInfo({ id: record.id }).then((res) => {
        this.mdl = res
        this.mdl['times'] = [res.start_time, res.end_time]
        this.confirmLoading = false
      })
    },
    async handleRemove (record) {
      this.openModal(surveyDel, { id: record.id, status: 3 }, '删除')
    },
    handleVisible () {
      this.visible = false
      setTimeout(() => {
        this.okHidden = false
      }, 350)
    },
    onSelectChange (selectedRowKeys, selectedRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectedRows = selectedRows
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    resetSearchForm () {
      this.queryParam = {}
    }
  }
}
</script>
